package com.ww.springboot.boot.baseTest.sync.volatil;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-11-18 16:54
 */
public class Demo1 {
    /**
     * 只能保证可见性 不能保证原子性(可能存在多个线程同时执行同一个赋值操作 导致操作相互覆盖)
     */
    private static volatile int i = 0;
    private static int total = 0;
    private static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 1000; i++) {
            Thread thread = new TestThread();
            thread.start();
        }
        Thread.sleep(3000);
        System.out.println(total);
        System.out.println(i);

    }

    static class TestThread extends Thread {

        public void run() {
            for (int j = 0; j < 1000; j++) {
                i = i + 1;
                //sync 保证原子性 只有一个线程能够获取锁
                synchronized(lock){
                    total++;
                }
            }
        }
    }
}
